import forgotPasswordApi from '@/api/user/forgotPasswordApi'
import { getAppNav } from '@/App'
import IEmailNotBlank from '@/model/form/common/IEmailNotBlank'
import { ToastSuccess } from '@/util/CommonUtil'
import Validator from '@/util/Validator'
import { Form, Button } from '@douyinfe/semi-ui'
import { Dispatch, SetStateAction } from 'react'

interface IForgotPasswordSendByEmail {
  loading: boolean
  setLoading: Dispatch<SetStateAction<boolean>>
  noPassword: boolean
}

export default function ForgotPasswordSendByEmail(
  props: IForgotPasswordSendByEmail
) {
  return (
    <Form
      disabled={props.loading}
      className="w-300 m-t-10"
      onSubmit={(form) => {
        if (props.loading) return
        submitClick(form as IEmailNotBlank, props.setLoading)
      }}
    >
      <Form.Input
        field="email"
        placeholder="邮箱"
        noLabel
        validate={Validator['emailValidate']}
        showClear
      />
      <Button
        block
        theme="solid"
        type="warning"
        size="large"
        loading={props.loading}
        htmlType="submit"
        className="m-t-10"
      >
        发送
      </Button>
      <Button
        disabled={props.loading}
        block
        className="m-t-10"
        onClick={() => {
          if (props.noPassword) {
            getAppNav()(-1)
          } else {
            getAppNav()('/login')
          }
        }}
      >
        {props.noPassword ? '返回' : '去登录'}
      </Button>
    </Form>
  )
}

// 点击提交按钮
function submitClick(
  form: IEmailNotBlank,
  setLoading: Dispatch<SetStateAction<boolean>>
) {
  setLoading(true) // 设置 loading状态

  forgotPasswordApi(form)
    .then(({ data }) => {
      ToastSuccess(data.msg)
      setLoading(false)
    })
    .catch(() => {
      setLoading(false)
    })
}
